"""
Power-up system for tank battle game
"""
import pygame
import random
import math
from typing import List, Dict, Optional
from utils.constants import PowerUpType
from utils.config import WINDOW_WIDTH, WINDOW_HEIGHT, RED, YELLOW
from utils.sound_manager import get_sound_manager


class PowerUp:
    """Power-up item that can be collected by player"""
    
    def __init__(self, power_type: str, x: int, y: int):
        """
        Initialize power-up
        
        Args:
            power_type: Type of power-up (PowerUpType enum)
            x: X coordinate
            y: Y coordinate
        """
        self.power_type = power_type
        self.x = x
        self.y = y
        self.width = 24
        self.height = 24
        self.collected = False
        self.spawn_time = pygame.time.get_ticks()
        
        # Visual properties
        self.color = self._get_power_up_color()
        self.rect = pygame.Rect(x, y, self.width, self.height)
        
        # Animation properties
        self.animation_offset = 0
        self.animation_speed = 0.1
        
    def _get_power_up_color(self) -> tuple:
        """Get power-up color based on type"""
        color_map = {
            PowerUpType.STEEL_BREAKER: YELLOW  # 钢墙破坏道具用黄色
        }
        return color_map.get(self.power_type, RED)
    
    def update(self, current_time: int):
        """Update power-up animation"""
        # 上下浮动动画
        self.animation_offset = math.sin(current_time * self.animation_speed) * 3
        
        # 检查是否超时消失（30秒后消失）
        if current_time - self.spawn_time > 30000:  # 30秒
            self.collected = True
    
    def draw(self, screen: pygame.Surface):
        """Draw power-up on screen"""
        if self.collected:
            return
            
        # 绘制道具主体
        draw_y = self.y + self.animation_offset
        pygame.draw.rect(screen, self.color, (self.x, draw_y, self.width, self.height))
        
        # 绘制边框
        pygame.draw.rect(screen, (255, 255, 255), (self.x, draw_y, self.width, self.height), 2)
        
        # 根据道具类型绘制图标
        if self.power_type == PowerUpType.STEEL_BREAKER:
            # 绘制锤子图标表示破坏钢墙
            pygame.draw.line(screen, (0, 0, 0), 
                           (self.x + 6, draw_y + 6), 
                           (self.x + 18, draw_y + 18), 3)
            pygame.draw.circle(screen, (0, 0, 0), 
                             (self.x + 18, draw_y + 18), 4)
    
    def check_collision(self, tank_rect: pygame.Rect) -> bool:
        """Check if tank collides with power-up"""
        if self.collected:
            return False
        return self.rect.colliderect(tank_rect)


class PowerUpManager:
    """Manages power-up spawning and collection"""
    
    def __init__(self):
        """Initialize power-up manager"""
        self.active_power_ups: List[PowerUp] = []
        self.player_power_ups: Dict[str, int] = {}  # power_type -> expiration_time
        self.last_spawn_time = 0
        self.spawn_interval = 15000  # 15秒生成一次道具
        
    def update(self, current_time: int, player_rect: pygame.Rect):
        """Update power-up manager"""
        # 更新活跃道具
        for power_up in self.active_power_ups[:]:
            power_up.update(current_time)
            
            # 检查玩家是否收集道具
            if power_up.check_collision(player_rect):
                self._collect_power_up(power_up, current_time)
                self.active_power_ups.remove(power_up)
            
            # 移除已收集或超时的道具
            elif power_up.collected:
                self.active_power_ups.remove(power_up)
        
        # 检查玩家道具是否过期
        expired_power_ups = []
        for power_type, expiration_time in self.player_power_ups.items():
            if current_time >= expiration_time:
                expired_power_ups.append(power_type)
        
        for power_type in expired_power_ups:
            del self.player_power_ups[power_type]
        
        # 尝试生成新道具
        self._try_spawn_power_up(current_time)
    
    def _try_spawn_power_up(self, current_time: int):
        """Try to spawn a new power-up"""
        if len(self.active_power_ups) >= 2:  # 最多同时存在2个道具
            return
            
        if current_time - self.last_spawn_time < self.spawn_interval:
            return
        
        # 随机选择道具类型
        power_types = [PowerUpType.STEEL_BREAKER]
        power_type = random.choice(power_types)
        
        # 生成随机位置（确保不与其他物体重叠）
        x = random.randint(50, WINDOW_WIDTH - 50)
        y = random.randint(50, WINDOW_HEIGHT - 50)
        
        # 创建新道具
        new_power_up = PowerUp(power_type, x, y)
        self.active_power_ups.append(new_power_up)
        self.last_spawn_time = current_time
    
    def _collect_power_up(self, power_up: PowerUp, current_time: int):
        """Collect a power-up"""
        power_up.collected = True
        
        # 设置道具过期时间
        expiration_time = current_time + 30000  # 30秒后过期
        self.player_power_ups[power_up.power_type] = expiration_time
        
        # 播放收集音效
        sound_manager = get_sound_manager()
        sound_manager.play_sound("power_up")
    
    def has_power_up(self, power_type: str) -> bool:
        """Check if player has active power-up"""
        return power_type in self.player_power_ups
    
    def get_remaining_time(self, power_type: str, current_time: int) -> int:
        """Get remaining time for power-up in seconds"""
        if power_type not in self.player_power_ups:
            return 0
        
        expiration_time = self.player_power_ups[power_type]
        remaining_ms = max(0, expiration_time - current_time)
        return remaining_ms // 1000  # 转换为秒
    
    def draw(self, screen: pygame.Surface):
        """Draw all active power-ups"""
        for power_up in self.active_power_ups:
            power_up.draw(screen)
    
    def clear(self):
        """Clear all power-ups (for level reset)"""
        self.active_power_ups.clear()
        self.player_power_ups.clear()
        self.last_spawn_time = 0


# 全局函数
def get_power_up_manager() -> PowerUpManager:
    """Get the global power-up manager instance"""
    if not hasattr(get_power_up_manager, "instance"):
        get_power_up_manager.instance = PowerUpManager()
    return get_power_up_manager.instance